//
//  EmailRegisteredViewController.m
//  CBT
//
//  Created by Mr.Zhang on 2018/11/23.
//  Copyright © 2018 Mr.Zhang. All rights reserved.
//

#import "EmailRegisteredViewController.h"

#import "RegisteredViewModel.h"

@interface EmailRegisteredViewController ()

@property (nonatomic,strong) id timer;

@property (nonatomic, strong) RegisteredViewModel *viewModel;

@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UITextField *codeTextField;
@property (weak, nonatomic) IBOutlet UITextField *emailTextField;
@property (weak, nonatomic) IBOutlet UITextField *invitationTextField;
@property (weak, nonatomic) IBOutlet UIView *invitationLineView;


@property (weak, nonatomic) IBOutlet UILabel *hasIDLabel;

@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *phoneRegisterBtn;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *emailTextFieldTopCon;

@end

@implementation EmailRegisteredViewController

#pragma mark - VC Life

- (void)viewDidLoad {
    [super viewDidLoad];
   
    if (self.showType == 1) {
        self.phoneRegisterBtn.hidden    = YES;
        self.invitationTextField.hidden = YES;
        self.invitationLineView.hidden  = YES;
    }
    
    [self showInfoMsg];
    [self inputAction];
    [self outPutAction];
}

-(void)dealloc {
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
}

- (void)showInfoMsg {
    if (self.showType == 1) {
        self.hasIDLabel.hidden = YES;
        self.loginBtn.hidden   = YES;
    }
    self.fd_prefersNavigationBarHidden = YES;
    
    [_codeButton setTitle:kLocalizedString(@"发送验证码", nil) forState:(UIControlStateNormal)];
    _emailTextField.placeholder = kLocalizedString(@"请输入您的邮箱号码", nil);
    _codeTextField.placeholder = kLocalizedString(@"请输入验证码", nil);
    _pwdTextField.placeholder  = kLocalizedString(@"请输入8-20位密码", nil);
    _invitationTextField.placeholder = kLocalizedString(@"请输入邀请码", nil);
    [_registerBtn setTitle:kLocalizedString(self.showType == 0 ? @"注册" : @"确定",nil) forState:(UIControlStateNormal)];
    _registerBtn.backgroundColor = UIColorFromRGB(0xff5101);

    [_phoneRegisterBtn setTitle:kLocalizedString(self.showType == 0 ? @"手机号注册" : @"手机号找回",  nil) forState:(UIControlStateNormal)];
    _hasIDLabel.text =  kLocalizedString(@"已有账号?", nil);
    [_loginBtn setTitle:kLocalizedString(@"立即登录", nil) forState:(UIControlStateNormal)];
}

#pragma mark - sendCode
-(void)sendCodeActionWithBtn:(UIButton *)btn {
    __block NSInteger second = 60;
    //全局队列    默认优先级
    dispatch_queue_t quene = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //定时器模式  事件源
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, quene);
    
    _timer = timer;
    
    //NSEC_PER_SEC是秒，＊1是每秒
    dispatch_source_set_timer(timer, dispatch_walltime(NULL, 0), NSEC_PER_SEC * 1, 0);
    //设置响应dispatch源事件的block，在dispatch源指定的队列上运行
    dispatch_source_set_event_handler(timer, ^{
        //回调主线程，在主线程中操作UI
        dispatch_async(dispatch_get_main_queue(), ^{
            if (second > 0) {
                btn.userInteractionEnabled = NO;
                btn.backgroundColor = UIColorFromRGB(0xd3d8fd);
                [btn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
                btn.layer.borderWidth = 0;
                [btn setTitle:[NSString stringWithFormat:@"%lds",(long)second] forState:UIControlStateNormal];
                second--;
            }
            else {
                //这句话必须写否则会出问题
                btn.userInteractionEnabled = YES;
                btn.backgroundColor   = [UIColor whiteColor];
                [btn setTitleColor:UIColorFromRGB(0x7889ff) forState:(UIControlStateNormal)];
                btn.layer.borderWidth = 1;
                dispatch_source_cancel(timer);
                [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
            }
        });
    });
    //启动源
    dispatch_resume(timer);
}

#pragma mark - Input

-(void)inputAction {
    @weak(self)
    //点击注册
    [[_registerBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.view endEditing:YES];
        [self_weak_ startClearBgColorLoading];
        [self_weak_.viewModel.registeredCommand execute:@{@"email":self_weak_.emailTextField.text,@"code":self_weak_.codeTextField.text,@"password":self_weak_.pwdTextField.text,@"avatar":self_weak_.invitationTextField.text,@"type":[NSString stringWithFormat:@"%ld",(long)self_weak_.showType]}];
    }];
    
    //发送邮箱验证码
    [[_codeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.view endEditing:YES];
        [self_weak_ startClearBgColorLoading];
        [self_weak_.viewModel.sendCodeCommand execute:@{@"email":self_weak_.emailTextField.text,@"type":self_weak_.showType == 0 ? @"1" : @"2"}];
    }];
    
    //立即登录
    [[_loginBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.navigationController popToRootViewControllerAnimated:YES];
    }];
    
    //手机号注册
    [[_phoneRegisterBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [self_weak_.navigationController popViewControllerAnimated:YES];
    }];
}

#pragma mark - OutPut

-(void)outPutAction {
    @weak(self)
    //注册成功
    [self.viewModel.registeredCommand.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
        if (self_weak_.showType == 1) {
            [self_weak_.navigationController popToRootViewControllerAnimated:YES];
        }
        else {
            [self_weak_.navigationController popToRootViewControllerAnimated:NO];
            [((AppDelegate*)[UIApplication sharedApplication].delegate) changeRootVC];
            [[NSUserDefaults standardUserDefaults] setValue:self_weak_.emailTextField.text forKey:@"emailAddress"];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"area"];
            [[NSUserDefaults standardUserDefaults] setValue:@"" forKey:@"phoneNumber"];
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
    }];
    
    //注册失败
    [self.viewModel.registeredCommand.errors subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
    }];
    
    //发送验证码成功
    [self.viewModel.sendCodeCommand .executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
        [self_weak_ sendCodeActionWithBtn:self_weak_.codeButton];
    }];
    
    //发送验证码失败
    [self.viewModel.sendCodeCommand.errors subscribeNext:^(id  _Nullable x) {
        [self_weak_ stopLoading];
    }];
}

#pragma mark - Lazy
- (RegisteredViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[RegisteredViewModel alloc]init];
    }
    return _viewModel;
}


@end
